#! /bin/bash
service php5-fpm start
service nginx start

install_myqsl()
{
    if [ -z $MYSQL_ROOT_PASSWORD ];then
        echo '$MYSQL_ROOT_PASSWORD required'
        exit 1
    fi

    apt-get -y install mysql-server
    service mysql start
    mysqladmin -uroot password $MYSQL_ROOT_PASSWORD

    MYSQL_HOST=127.0.0.1
    MYSQL_USERNAME=root
    MYSQL_PASSWORD=$MYSQL_ROOT_PASSWORD
}

install_we7()
{
    cd $WWW_DIR
    unzip $WWW_DIR/we7.zip
    chmod -R 0777 $WWW_DIR

    if [ -f /etc/nginx/sites-enabled/default ];then
        rm /etc/nginx/sites-enabled/default
    fi

    cp /usr/src/install/nginx.conf /etc/nginx/sites-enabled/we7
    echo "date.timezone=PRC" > /etc/php5/fpm/conf.d/date.ini

    service nginx restart
    service php5-fpm restart

    curl -b "action=db" -d "do=continue&db[server]=$MYSQL_HOST&db[username]=$MYSQL_USERNAME&db[password]=$MYSQL_PASSWORD&db[name]=$WE7_DB_NAME&db[prefix]=$WE7_TABLE_PREFIX&user[username]=$WE7_ADMIN_USERNAME&user[password]=$WE7_ADMIN_PASSWORD" http://127.0.0.1/install.php
}

lock='/usr/src/install/.lock'
if [ ! -f $lock ];then
    
# if [ -z $LINK_MYSQL ];then
    install_myqsl
    install_we7

# else    
#     if [ -z MYSQL_LINK_NAME || -z $MYSQL_LINK_USERNAME || -z $MYSQL_LINK_PASSWORD ];then
#         echo '$MYSQL_LINK_NAME and $MYSQL_LINK_USERNAME and $MYSQL_LINK_PASSWORD required'
#         exit 1
#     fi
#     MYSQL_LINK_PORT=${MYSQL_LINK_PORT:-3306}
#     MYSQL_LINK_HOST_KEY=${MYSQL_LINK_NAME}_PORT_${MYSQL_LINK_PORT}_TCP_ADDR

#     MYSQL_HOST=${!MYSQL_LINK_PORT}
#     MYSQL_USERNAME=${!MYSQL_LINK_USERNAME}
#     MYSQL_PASSWORD=${!MYSQL_LINK_PASSWORD}
# fi

# WE7_DB_NAME=${WE7_DB_NAME:-we7}
# WE7_ADMIN_USERNAME=${WE7_ADMIN_USERNAME:-admin}
# WE7_ADMIN_PASSWORD=${WE7_ADMIN_PASSWORD:-admin}
# WE7_TABLE_PREFIX=${WE7_TABLE_PREFIX:-we7_}

    echo '' > $lock
else
    service mysql start
fi

while :
do
:
done
